const { declare } = require('@babel/helper-plugin-utils');
const importModule = require('@babel/helper-module-imports');

module.exports = declare((api, options, dirname) => {
	api.assertVersion(7)
	return {
		visitor: {
			Program: {
				enter(path, state) {
					path.traverse({
						ImportDeclaration(curpath) {
							let requirePath = curpath.get('source')
							let requireValue = requirePath.node.value
							if(requireValue === options.trackerPath) {
								let importPath = curpath.get('specifiers')[0].get('local')
								let importIdentifier = importPath.node.name
								state.importIdentifier = importIdentifier
								curpath.stop()
							}
						}
					})
					if(!state.importIdentifier) {
						state.importIdentifier  = importModule.addDefault(path, options.trackerPath,{
							nameHint: path.scope.generateUid(options.trackerPath)
						}).name
						state.trackerAST = api.template.statement(`${state.importIdentifier}()`)();// 埋点代码的 AST
					}
				}
			},
			'ClassMethod|ArrowFunctionExpression|FunctionExpression|FunctionDeclaration'(path, state) {
				const bodyPath = path.get('body');
				if (bodyPath.isBlockStatement()) { // 有函数体就在开始插入埋点代码
						bodyPath.node.body.unshift(state.trackerAST);
				} else { // 没有函数体要包裹一下，处理下返回值
						const ast = api.template.statement(`{%%importName%%();return %%PREV_BODY%%;}`)({PREV_BODY: bodyPath.node,importName: state.importIdentifier});
						bodyPath.replaceWith(ast);
				}
			},
			'JSXExpressionContainer'(path, state) {
				// console.log(path)
			}
		}
	}
})